import {
  AlipayCircleOutlined,
  AlipayOutlined,
  LockOutlined,
  MobileOutlined,
  TaobaoOutlined,
  UserOutlined,
  WeiboCircleOutlined,
  WeiboOutlined,
} from '@ant-design/icons';
import {
  LoginFormPage,
  ProConfigProvider,
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormText,
} from '@ant-design/pro-components';
import { useIntl, history, useModel, Link } from '@umijs/max';
import { Divider, Form, message, Space, Tabs, theme } from 'antd';
import React, { useState } from 'react';
import type { CSSProperties } from 'react';
import { checkUsername, getCode, getCurrentUserInfo, login, userLoginWithEmail } from '@/services/user/yonghujiekou'
import { flushSync } from 'react-dom';
import { useForm } from 'antd/es/form/Form';
type LoginType = 'email' | 'account';

const iconStyles: CSSProperties = {
  color: 'rgba(0, 0, 0, 0.2)',
  fontSize: '18px',
  verticalAlign: 'middle',
  cursor: 'pointer',
};

const Login: React.FC = () => {
  const [type, setType] = useState<LoginType>('account');
  const { token } = theme.useToken();
  const [userLoginState, setUserLoginState] = useState({});
  const { initialState, setInitialState } = useModel('@@initialState');
  const intl = useIntl();
  const [form] = Form.useForm();
  const [emailState, setEmailState] = useState<boolean>(false);


  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };



  const loginWithUsername = async (values: API.UserLoginRequest) => {
    try {
      // 登录
      const res = await login({ ...values });
      if (res.code === 0) {
        processSuc(res.data);
      } else {
        message.error(res.message)
      }
      console.log(res);
      // 如果失败去设置用户错误信息
      // setUserLoginState(res);
    } catch (error) {
      const defaultLoginFailureMessage = '登录失败，请重试！';
      message.error(defaultLoginFailureMessage);
    }
  };

  const loginWithEmail = async (values: API.UserLoginWithEmailRequest) => {
    try {

      // 登录
      const res = await userLoginWithEmail({ ...values });
      if (res.code === 0) {
        processSuc(res.data);
      } else {
        message.error(res.message)
      }
      console.log(res);
      // 如果失败去设置用户错误信息
      // setUserLoginState(res);
    } catch (error) {
      const defaultLoginFailureMessage = '登录失败，请重试！';
      message.error(defaultLoginFailureMessage);
    }
  };

  const validEmails = async () => {
    const x = await checkUsername(form.getFieldValue('email'))
    if (x.code == 0) {
      message.error('邮箱未注册！')
      setEmailState(true)
      return false;
    }
    setEmailState(false)
    return true;
  }

  const processSuc = async (token: any) => {
    const defaultLoginSuccessMessage = intl.formatMessage({
      id: 'pages.login.success',
      defaultMessage: '登录成功！',
    });
    localStorage.setItem('Authorization', token ? token : '');
    // 尝试获取用户信息
    const userInfo = true;
    if (userInfo) {
      // 如果成功获取用户信息，则进行跳转
      await fetchUserInfo();
      message.success(defaultLoginSuccessMessage);
      const urlParams = new URL(window.location.href).searchParams;
      history.push(urlParams.get('redirect') || '/welcome');
      return;
    } else {
      // 如果获取用户信息失败，则提示错误信息
      message.error('登录失败，请重试！');
      return
    }
  }

  const vaildEmail = (email: any) => {
    const emailPattern = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
    if (!emailPattern.test(email)) {
      message.error('邮箱格式错误！');
      return false;
    }
    
    return true
  }

  return (
    <div
      style={{
        backgroundColor: 'white',
        height: '100vh',
      }}
    >
      <LoginFormPage
        form={form}
        backgroundImageUrl="https://mdn.alipayobjects.com/huamei_gcee1x/afts/img/A*y0ZTS6WLwvgAAAAAAAAAAAAADml6AQ/fmt.webp"
        // logo="https://github.githubassets.com/images/modules/logos_page/Octocat.png"
        backgroundVideoUrl="https://gw.alipayobjects.com/v/huamei_gcee1x/afts/video/jXRBRK_VAwoAAAAAAAAAAAAAK4eUAQBr"
        title="GroupHy"
        containerStyle={{
          backgroundColor: 'rgba(0, 0, 0,0.65)',
          backdropFilter: 'blur(4px)',
        }}
        subTitle="数据分析平台"
        onFinish={async (values: any) => {
          if (type === 'account') {
            console.log(type)
            await loginWithUsername(values as API.UserLoginRequest);
          } else {
            await loginWithEmail(values as API.UserLoginWithEmailRequest);
          }

        }}
      >
        <Tabs
          centered
          activeKey={type}
          onChange={(activeKey) => setType(activeKey as LoginType)}
        >
          <Tabs.TabPane key={'account'} tab={'账号密码登录'} />
          <Tabs.TabPane key={'email'} tab={'邮箱登录'} />
        </Tabs>
        {type === 'account' && (
          <>
            <ProFormText
              name="username"
              placeholder={'请输入用户名'}
              rules={[
                {
                  required: true,
                  message: '请输入用户名!',
                },
              ]}
              initialValue={'admin'}
            />
            <ProFormText.Password
              name="password"

              placeholder={'请输入密码'}
              rules={[
                {
                  required: true,
                  message: '请输入密码！',
                },
              ]}
              initialValue={'Admin@123'}
            />
          </>
        )}
        {type === 'email' && (
          <>
            <ProFormText
              name="email"
              placeholder={'请输入邮箱'}
              rules={[
                {
                  required: true,
                  message: '请输入邮箱！',
                },
                {
                  // pattern: /^1\d{10}$/,
                  pattern: /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/,
                  message: '邮箱格式错误！',
                },
              ]}
            />
            <ProFormCaptcha

              captchaProps={{
                size: 'large',
              }}
              placeholder={'请输入验证码'}
              captchaTextRender={(timing: any, count: any) => {
                if (timing) {
                  return `${count} s${'获取验证码'}`;
                }
                return '获取验证码';
              }}
              name="code"
              rules={[
                {
                  required: true,
                  message: '请输入验证码！',
                },
              ]}
              onGetCaptcha={async () => {
                const email = form.getFieldValue('email')
                if (email === 'undefined' || !email) {
                  message.error('请输入邮箱')
                  return Promise.reject();
                }
                const x = vaildEmail(email)
                if (!x) {
                  return Promise.reject();
                }
                if(emailState){
                  return Promise.reject();
                }
                const y = await validEmails()
                if (!y) {
                  return Promise.reject();
                }
                const res = await getCode(email)
                if (res.code === 0) {
                  message.success('验证码发送成功！')
                } else {
                  message.error('验证码发送失败！')
                  return Promise.reject()
                }
              }}
            />
          </>
        )}
        <div
          style={{
            marginBlockEnd: 24,
          }}
        >
          {/* <ProFormCheckbox noStyle name="autoLogin">
            自动登录
          </ProFormCheckbox>
          <a

            href='/user/register'
          >

          </a> */}
          <Link to={'/user/register'} style={{
            float: 'right',
            marginBottom: '14px',
          }}>注册</Link>
        </div>
      </LoginFormPage>
    </div>
  );
};

export default () => {
  return (
    <ProConfigProvider dark>
      <Login />
    </ProConfigProvider>
  );
};
